package com.deer.wms.ASN.manage.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.deer.wms.ASN.manage.constant.AsnManageConstant;
import com.deer.wms.ASN.manage.dao.QcRecordMapper;
import com.deer.wms.ASN.manage.model.in.AcceptRecord;
import com.deer.wms.ASN.manage.model.qc.*;
import com.deer.wms.ASN.manage.service.AcceptRecordService;
import com.deer.wms.ASN.manage.service.QcRecordFileService;
import com.deer.wms.ASN.manage.service.QcRecordService;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.inventory.constant.InventoryConstant;
import com.deer.wms.inventory.model.Inventory.InventoryTransact;
import com.deer.wms.inventory.service.InventoryTransactService;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.project.root.service.SuperServiceImpl;
import com.deer.wms.project.root.util.BeanUtils;
import com.deer.wms.project.root.util.DateUtils;
import com.deer.wms.system.manage.constant.SystemManageConstant;
import com.deer.wms.system.manage.service.CodeRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author guo
 * @since 2020/01/15
 */
@Service
@Transactional
public class QcRecordServiceImpl extends SuperServiceImpl<QcRecordMapper, QcRecord> implements QcRecordService {

    @Autowired
    private QcRecordMapper qcRecordMapper;
    @Autowired
    private QcRecordService qcRecordService;
    @Autowired
    private QcRecordFileService qcRecordFileService;
    @Autowired
    private AcceptRecordService acceptRecordService;
    @Autowired
    private CodeRuleService codeRuleService;
    @Autowired
    private InventoryTransactService inventoryTransactService;

    @Override
    public List<QcRecordDto> findList(QcRecordCriteria criteria) {
        return qcRecordMapper.findList(criteria);
    }

    /**
     * 归档
     *
     * @param detailNo
     * @param currentUser
     */
    @Override
    public void createFile(String detailNo, CurrentUser currentUser) {
        QcRecord qcRecord = qcRecordService.getOneByField("detail_no", detailNo);

        Integer fileUserId = currentUser.getUserId();
        String fileUserName = currentUser.getUserName();
        String fileTime = DateUtils.getNowDateTimeString();

        QcRecordFile qcRecordFile = new QcRecordFile();
        BeanUtils.copyProperties(qcRecordFile, qcRecord);

        qcRecordFile.setCreateUserId(fileUserId);
        qcRecordFile.setCreateUserName(fileUserName);
        qcRecordFile.setCreateTime(fileTime);

        qcRecordFileService.save(qcRecordFile);
        qcRecordService.deleteByDetailNo(detailNo);
    }

    @Override
    public void deleteByDetailNo(String detailNo) {
        qcRecordMapper.deleteByDetailNo(detailNo);
    }

    @Override
    public void qcResult(QcResultCriteria criteria,CurrentUser currentUser) {
        //Step1.根据收货单生成质检单
        AcceptRecord acceptRecord = acceptRecordService.getOneByField("accept_record_code", criteria.getBillCode());
        //需要判断是否已质检
        if (ObjectUtil.notEqual(AsnManageConstant.ACCEPT_QC_STATE_TODO, acceptRecord.getQcState())) {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "收货单：" + acceptRecord.getAcceptRecordCode() + "已质检");
        }
        QcRecord qcRecord = processQcData(acceptRecord);
        qcRecord.setQcRecordCode(codeRuleService.generateCode(SystemManageConstant.CORE_RULE_QC));
        // 设置合格，不合格，让步数量 质检结果 质检时间
        qcRecord.setQualifiedQuantity(criteria.getQualifiedQuantity());
        qcRecord.setFiedQuantity(criteria.getFiedQuantity());
        qcRecord.setConcessionQuantity(criteria.getConcessionQuantity());
        // 设置实检数量,操作员,质检结果，质检时间
        qcRecord.setRealQuantity(acceptRecord.getQuantity());
        qcRecord.setQcUserId(currentUser.getUserId());
        qcRecord.setQcUserName(currentUser.getUserName());
        qcRecord.setQcResult(criteria.getQcResult());
        qcRecord.setQcTime(DateUtil.now());
        qcRecord.setQcBillNo(acceptRecord.getAsnDetailNo());
//        if(criteria.getAbnormalBillNo()!=null){
//            qcRecord.setAbnormalBillNo(criteria.getAbnormalBillNo());
//        }
//        if(criteria.getEspeciallyBillNo()!=null){
//            qcRecord.setEspeciallyBillNo(criteria.getEspeciallyBillNo());
//        }

        qcRecordService.save(qcRecord);

        //Step2.生成库存事务
        InventoryTransact inventoryTransact = toStockRequest(qcRecord, criteria.getQcResult());
        inventoryTransactService.run(inventoryTransact);

        //Step3.更新收货单的质检状态
        if (AsnManageConstant.QC_RESULT_UNQ.equals(criteria.getQcResult())) {
            //不合格 继续冻结 记录原因
            acceptRecord.setQcState(AsnManageConstant.ACCEPT_QC_STATE_CHECKED_FAIL);
        } else if (AsnManageConstant.QC_RESULT_QUA.equals(criteria.getQcResult())) {
            acceptRecord.setQcState(AsnManageConstant.ACCEPT_QC_STATE_CHECKED_PASS);
        } else {
            acceptRecord.setQcState(AsnManageConstant.ACCEPT_QC_STATE_CHECKED_CON);
        }
        acceptRecordService.updateById(acceptRecord);
    }

    /**
     * 根据质检单生成库存事务
     *
     * @param qcRecord 质检单
     * @return InventoryTransact 库存事务
     */
    private InventoryTransact toStockRequest(QcRecord qcRecord, Integer result) {
        InventoryTransact inventoryTransact = new InventoryTransact();
        //Step1.准备数据
        //仓库
        inventoryTransact.setWareId(qcRecord.getWareId());
        inventoryTransact.setWareName(qcRecord.getWareName());
        //物料
        inventoryTransact.setItemCode(qcRecord.getItemCode());
        inventoryTransact.setItemName(qcRecord.getItemName());
        //批次
        inventoryTransact.setFromBatchId(qcRecord.getBatchId());
        inventoryTransact.setFromBatchName(qcRecord.getBatchName());
        //创建人 时间
        inventoryTransact.setCreateUserId(qcRecord.getQcUserId());
        inventoryTransact.setCreateUserName(qcRecord.getQcUserName());
        inventoryTransact.setCreateTime(DateUtil.now());
        //事务类型
        if (AsnManageConstant.QC_RESULT_UNQ.equals(result)) {
            //不合格 继续冻结 记录原因
            inventoryTransact.setTransactType(InventoryConstant.INVENTORY_FREEZE);
            inventoryTransact.setStateDis("不合格");
        } else {
            //合格 解冻
            inventoryTransact.setTransactType(InventoryConstant.INVENTORY_UNFREEZE);
        }

        //来源单据号
        inventoryTransact.setBillNo(qcRecord.getQcBillNo());

        //Step2.保存，返回
        inventoryTransactService.save(inventoryTransact);
        return inventoryTransact;
    }

    /**
     * 生成质检单
     *
     * @param acceptRecord 收货单
     * @return QcRecord
     */
    private QcRecord processQcData(AcceptRecord acceptRecord) {
        QcRecord qcRecord = new QcRecord();
        //来源单号
        qcRecord.setAcceptRecordId(acceptRecord.getId());
        qcRecord.setAcceptRecordCode(acceptRecord.getAcceptRecordCode());
        //仓库
        qcRecord.setWareId(acceptRecord.getWareId());
        qcRecord.setWareName(acceptRecord.getWareName());
        //物料
        qcRecord.setItemCode(acceptRecord.getItemCode());
        qcRecord.setItemName(acceptRecord.getItemName());
        qcRecord.setPackDetailId(acceptRecord.getPackDetailId());
        qcRecord.setPackDescribe(acceptRecord.getPackDescribe());
        //批次
        qcRecord.setBatchId(acceptRecord.getBatchId());
        qcRecord.setBatchName(acceptRecord.getBatchName());
        //数量
        qcRecord.setQcQuantity(acceptRecord.getQuantity());

        return qcRecord;
    }

}
